<template>
    <base-breadcrumb :title="title" :breadcrumb="!isAudit">
        <!-- 期中结算报送审批编辑 -->
        <a-form-model
            ref="ruleForm"
            :model="form"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
            :rules="editModel != 0 ? rules : {}"
        >
            <a-spin :spinning="loading">
                <!-- 表格 -->
                <a-card :bordered="false">
                    <title-name title="基本信息"></title-name>
                    <custom-form
                        :formList="formList"
                        :form="form"
                        :isEmit="false"
                        :editModel="editModel == 0 ? '' : ''"
                        @select="selectOrg"
                        @getProjectInfo="getProjectInfoFn"
                    >
                        <template v-slot:table>
                            <a-form-model-item label=" " :colon="false">
                                <!-- 表格 -->
                                <s-table
                                    class="mb20"
                                    bordered
                                    ref="table"
                                    tableLayout="fixed"
                                    size="default"
                                    rowKey="id"
                                    :columns="columns"
                                    :data="loadData"
                                    :alert="true"
                                    show-size-changer
                                    show-quick-jumper
                                    :showPagination="false"
                                >
                                    <template
                                        v-for="col in ['notContainTaxFee', 'taxFee', 'containTaxFee', 'remark']"
                                        :slot="col"
                                        slot-scope="text, record, index"
                                    >
                                        <div :key="col" class="form-item">
                                            <template>
                                                <template v-if="editModel != 0">
                                                    <BaseInput
                                                        v-if="col === 'remark'"
                                                        :class="col === 'remark' ? 'remark' : ''"
                                                        :disabled="editModel == 0"
                                                        v-model="record[col]"
                                                    >
                                                    </BaseInput>
                                                    <span v-else-if="col === 'containTaxFee'">{{ text }} </span>

                                                    <BaseInputNumber
                                                        v-else
                                                        v-model="record[col]"
                                                        :disabled="editModel == 0"
                                                        :precision="2"
                                                        @change="change(index)"
                                                    >
                                                    </BaseInputNumber>
                                                </template>
                                                <template v-else> {{ text }}</template>
                                            </template>
                                        </div></template
                                    ></s-table
                                >
                            </a-form-model-item>
                        </template>

                        <!-- 附件上传 -->
                        <template #fileList>
                            <template v-if="editModel != 0">
                                <l-table businessCode="BM27" :uploadArrys.sync="form.fileList"></l-table>
                                <!-- <div class="file_prompt">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div> -->
                            </template>
                            <file-link v-else :fileList="form.fileList" style="margin-top: -3px"></file-link>
                        </template>
                    </custom-form>
                </a-card>

                <!-- 页脚操作栏 -->
                <div class="btn_box page-btn-right-top" v-if="editModel != 0 && !isConsultation">
                    <a-button
                        class="button_right"
                        v-if="form.status == 'REJECTED'"
                        type="primary"
                        :disabled="isName"
                        :loading="loading.REJECTED"
                        @click="handleSubmit('REJECTED')"
                        >保存</a-button
                    >
                    <a-button
                        v-else
                        class="button_right"
                        type="primary"
                        :loading="loading.DRAFT"
                        :disabled="isName"
                        @click="handleSubmit('DRAFT')"
                        >保存草稿</a-button
                    >
                    <a-button
                        class="button_right"
                        type="primary"
                        :loading="loading.SUBMITTED"
                        @click="handleSubmit('SUBMITTED')"
                        :disabled="isName"
                        >提交</a-button
                    >
                    <a-button type="primary" @click="handleActiveClose">关闭</a-button>
                </div>
                <div class="btn_box page-btn-right-top" v-else-if="!isConsultation">
                    <a-button type="primary" @click="handleActiveClose">关闭</a-button>
                </div>
            </a-spin>
        </a-form-model>
        <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
</template>

<script>
import { getSubmission, addOrUpdateSubmission, checkName } from '@/api/businessAffairs/revenueAndCost'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectPersonModal from '@/components/SelectPersonModal'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import moment from 'moment'
import { position } from './model.js'
import { getProjectInfo } from '@/api/businessAffairs/revenueAndCost'
import _ from 'lodash'
const columns = [
    {
        title: '项目/金额',
        dataIndex: 'projectFeeName'
    },
    {
        title: '1.不含增值税(万元)',
        dataIndex: 'notContainTaxFee',
        scopedSlots: { customRender: 'notContainTaxFee' }
    },
    {
        title: '2.增值税(万元)',
        dataIndex: 'taxFee',
        scopedSlots: { customRender: 'taxFee' }
    },
    {
        title: '含增值税(万元)(1+2)',
        dataIndex: 'containTaxFee',
        scopedSlots: { customRender: 'containTaxFee' }
    },
    {
        title: '备注',
        dataIndex: 'remark',
        scopedSlots: { customRender: 'remark' }
    }
]
export default {
    name: 'a' + Date.now(),
    extends: new BaseEditPage(),
    components: {
        SelectPersonModal
    },
    data() {
        this.columns = columns
        return {
            loading: false, // 加载控件
            visible: false, //人员选择控件
            editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
            form: {
                sendName: '',
                projectId:null,
                structureType: '',
                areaOfStructure: '',
                reportFee: 0,
                reportRate: 0,
                guaranteedFee: 0,
                guaranteedRate: 0,
                midInfoDetail: [
                    {
                        containTaxFee: null,
                        notContainTaxFee: null,
                        taxFee: null,
                        remark: null,
                        projectFeeName: '报审值'
                    },
                    {
                        containTaxFee: null,
                        notContainTaxFee: null,
                        taxFee: null,
                        remark: null,
                        projectFeeName: '保底值'
                    },
                    {
                        containTaxFee: null,
                        notContainTaxFee: null,
                        taxFee: null,
                        remark: null,
                        projectFeeName: '实际成本'
                    }
                ]
            }, // 表单
            id: '',
            loadData: () => {
                if (this.form.midInfoDetail.length > 0) {
                    return new Promise((resolve, reject) => {
                        resolve({
                            data: this.form.midInfoDetail
                        })
                    })
                }
            },
            loadingBtn: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            rules: {
                name: [{ required: true, message: '请输入' }],
                partId: [{ required: true, message: '请选择' }],
                contractInfo: [{ required: true, message: '请输入' }],
                overRideContractFee: [{ required: true, message: '请选择' }]
            }, // 校验规则
            init: false, // 初始化控件
            isName: false,
            disabledDateList: [],
            titles: ['期中结算报送审批 查看', '期中结算报送审批 编辑', '期中结算报送审批 新增'],
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    props: {
        // 是否作为审批详情
        isAudit: {
            type: Boolean,
            default: false
        },
        // 是否作为意见征询
        isConsultation: {
            type: Boolean,
            default: false
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.editModel = 0
                    })
                }
            }
        }
    },
    async mounted() {
        // 不为添加时请求详情
        if (this.editModel != 2) {
            this.loading = true
            getSubmission({ id: this.id })
                .then((res) => {
                    this.loading = false
                    console.log(res)
                    this.form = res[1].data
                    console.log(this.form)

                    this.$nextTick(() => {
                        this.init = true
                        if (this.form.overRideContractFee != null) {
                            this.form.overRideContractFee = this.form.overRideContractFee ? 1 : 0
                        }

                        this.$refs.table.refresh(true)
                    })
                })
                .catch(() => {
                    this.loading = false
                })
        } else {
            this.form.projectId = this.$userInfo().currentPost.projectId;
            this.$nextTick(() => {
                this.init = true
            })
        }
      //获取通过获取流程配置值
       this.processConfig = await this.$getConfigFn('comm_mid_settlement_submit_approve')
    },
    computed: {
        formList() {
            return [
               {
                    label: '所属单位',
                    type: 'orgTree',
                    keyName: 'projectId',
                    rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
                    span: 16,
                    isAutoSelectFirst: true,
                    isNeedAuth:true ,
                    checkStrictly: true,
                    disabled: true,
                    viewName: "viewName",
                },
                // {
                //     type: SelectSubCompany,
                //     keyName: 'branchCompanyId',
                //     label: '所属分公司',
                //     disabled: true,
                //     attrs: {
                //         isDefaultSelected: this.editModel == 2,
                //         autoSelected: this.editModel == 2
                //     }
                // },
                // {
                //     type: SelectProject,
                //     keyName: 'projectId',
                //     label: '所属项目',
                //     disabled: true,
                //     attrs: {
                //         isDefaultSelected: this.editModel == 2,
                //         autoSelected: this.editModel == 2,
                //         keyValue: 'branchCompanyId',
                //         isClear: this.editModel == 2,
                //         isEdit: this.editModel != 2,
                //         form: this.form
                //     },
                //     selectChange: (e) => {
                //         getProjectInfo({ projectId: e.code }).then((res) => {
                //             this.form.sendName = res.data.constructionName
                //             this.form.structureType = res.data.structureTypeName
                //             this.form.areaOfStructure = res.data.contractTotalArea * 10000
                //         })
                //     }
                // },
                {
                    keyName: 'name',
                    type: 'BaseInput',
                    disabled: this.editModel == 0,
                    label: '名称',
                    change: (e) => {
                        this.debounce()
                    }
                },
                {
                    label: '结算部位',
                    keyName: 'partId',
                    type: 'a-select',
                    disabled: this.editModel == 0,
                    data: position
                },
                {
                    keyName: 'sendName',
                    type: 'BaseInput',
                    disabled: true,
                    label: '发包人全称'
                },
                {
                    keyName: 'structureType',
                    type: 'BaseInput',
                    disabled: true,
                    label: '结构类型'
                },
                {
                    keyName: 'areaOfStructure',
                    type: 'BaseInput',
                    disabled: true,
                    label: '建筑面积m²'
                },
                {
                    keyName: 'overRideContractFee',
                    type: 'a-radio-group',
                    disabled: this.editModel == 0,
                    label: '是否突破合同进行结算',
                    data: [
                        {
                            label: '否',
                            value: 0
                        },
                        {
                            label: '是',
                            value: 1
                        }
                    ]
                },
                {
                    keyName: 'contractInfo',
                    type: 'BaseTextarea',
                    disabled: this.editModel == 0,
                    label: '合同内期中结算相关说明',
                    span: 24
                },

                {
                    slot: true,
                    customItemSlot: true,
                    keyName: 'table',
                    span: 24
                },
                {
                    keyName: 'guaranteedFee',
                    type: 'BaseInputNumber',
                    precision: 2,
                    disabled: true,
                    label: '保底利润额(含税)(万元)'
                },
                {
                    keyName: 'guaranteedRate',
                    type: 'BaseInputNumber',
                    precision: 2,
                    disabled: true,
                    label: '保底利润率%'
                },
                {
                    keyName: 'reportFee',
                    type: 'BaseInputNumber',
                    precision: 2,
                    disabled: true,
                    label: '报审利润额(含税)(万元)'
                },
                {
                    keyName: 'reportRate',
                    type: 'BaseInputNumber',
                    precision: 2,
                    disabled: true,
                    label: '报审利润率%'
                },
                {
                    slot: true,
                    keyName: 'fileList',
                    label: '附件上传',
                    span: 24
                }
            ]
        }
    },

    methods: {
        //选择单位
        selectOrg(val) {
            if (val && val.length) {
                this.form.branchComId = val[val.length - 2].orgId
            }
        },
        //获取项目详情
        getProjectInfoFn(e) {
            getProjectInfo({ projectId: e.projectId }).then((res) => {
                    this.form.sendName = res.data.constructionName
                    this.form.structureType = res.data.structureTypeName
                    this.form.areaOfStructure = res.data.contractTotalArea * 10000
                })
        },
        // 防抖
        debounce: _.debounce(function () {
            checkName({ name: this.form.name }).then((res) => {})
            this.isName = !res.data
            if (!this.isName) {
                this.$message.warning('名称不能重复!')
            }
        }, 1000),
        /**
         * 输入框事件
         */
        change(index) {
            this.$nextTick(() => {
                if (
                    this.form.midInfoDetail[index].taxFee != null &&
                    this.form.midInfoDetail[index].notContainTaxFee != null
                ) {
                    this.form.midInfoDetail[index].containTaxFee =
                        this.form.midInfoDetail[index].taxFee + this.form.midInfoDetail[index].notContainTaxFee
                } else if (
                    this.form.midInfoDetail[index].taxFee == null &&
                    this.form.midInfoDetail[index].notContainTaxFee == null
                ) {
                    this.form.midInfoDetail[index].containTaxFee = 0
                }

                if (index == 1 || index == 2) {
                    this.form.guaranteedFee =
                        this.form.midInfoDetail[1].containTaxFee - this.form.midInfoDetail[2].containTaxFee
                    this.form.guaranteedRate =
                        (this.form.guaranteedFee / this.form.midInfoDetail[1].containTaxFee) * 100
                }
                if (index == 0 || index == 2) {
                    this.form.reportFee =
                        this.form.midInfoDetail[0].containTaxFee - this.form.midInfoDetail[2].containTaxFee
                    this.form.reportRate = (this.form.reportFee / this.form.midInfoDetail[0].containTaxFee) * 100
                }
                // this.$refs.table.refresh(true)
            })
        },

        validateTable(list) {
            let flag = false

            list.forEach((item) => {
                if (item.notContainTaxFee == null || item.containTaxFee == null) {
                    flag = true
                }
            })
            if (flag) {
                this.$message.warning('请完善表格后提交')
            }
            return flag
        },
        validateForm() {
            let flag = false
            this.$refs.ruleForm.validate((e) => {
                if (e) {
                    flag = true
                }else {
                  this.$message.warning('请填写完所有必填项信息')
                }
            })
            return flag
        },
        /**
         * 提交表单
         */
        async handleSubmit(status) {
            this.setProcessConfig = null;
            if (status == 'SUBMITTED') {
                // 校验表单
                if (!this.validateForm() || this.validateTable(this.form.midInfoDetail)) {
                    return
                }
            }

            this.loading = true
            this.loadingBtn[status] = true
            this.form.status = status
            let form = this.$clone(this.form)
            form.postCode = this.$userInfo().currentPost.postCode
            if (form.partId) {
                form.partName = position.filter((i) => i.value == form.partId)[0].label
            }
            if (form.overRideContractFee == 0) {
                form.overRideContractFee = false
            } else if (form.overRideContractFee == 1) {
                form.overRideContractFee = true
            }

            const [err, res] = await addOrUpdateSubmission(form)
            this.loading = false
            this.loadingBtn[status] = false
            if (!err) {
                this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
                if(status =='SUBMITTED') {
                //提交时，返回id
                    this.businessId = res.data || this.id;
                    this.setProcessConfig = this.processConfig;
                    return
                }else{
                  this.$multiTab.close()
                 }
            } else {
                this.$message.warning(err.data.message)
            }
        }
    }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
    .ant-input:not([disabled]),
    .ant-select:not(.ant-select-disabled) .ant-select-selection,
    .ant-calendar-picker-input,
    .ant-input-number:not([disabled]),
    .ant-cascader-picker {
        border-color: #e4ac0b;
        background-color: #fff9e8;
    }
    .remark {
        .ant-input {
            border-color: inherit;
            background-color: initial;
        }
    }
}
</style>
